const mongoose = require('mongoose')
let Schema = mongoose.Schema
const jwt = require('jwt-simple')
const SECRET = 'AMC_MERCHANT_SECRET'   // secret key

// validate username
let validateUsername = username => {
    return (username.length > 2 || username.length < 10);
};

let MerchantSchema = new mongoose.Schema({
    // merchant name
    merchantName: {
        type: String,
        unique: 'Username already exists',
        required: 'Please fill in a username',
        lowercase: true,
        validate: [validateUsername, "Username's length should be 2-10 bits."],
        trim: true
    },

    // merchant password
    password: String,

    // merchant address
    address: String,

    // merchant personal head picture
    headPic: {
        type: String,
        default: 'https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=1466427980,97355553&fm=26&gp=0.jpg'
    },

    // merchant personal id-card picture
    idCardPic: {
        type: String,
        default: 'https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=1466427980,97355553&fm=26&gp=0.jpg'
    },

    meta: {         //date note
        createAt: {
            type: Date,
            default: Date.now()
        },
        updateAt: {
            type: Date,
            default: Date.now()
        }
    }
})

MerchantSchema.pre('save', function (next) {
    let user = this
    if (this.isNew) {
        this.meta.createAt = this.meta.updateAt = Date.now()
    } else {
        this.meta.updateAt = Date.now()
    }
    //encode password
    user.password = jwt.encode(user.password, SECRET)
    next()
})

//decode password and checking
MerchantSchema.methods = {
    comparePassword: function (_password, cb) {
        let dpassword = jwt.decode(this.password, SECRET)
        cb(_password === dpassword)
    }
}

MerchantSchema.statics = {
    findById: function (id, cb) {
        return this
            .findOne({ _id: id })
            .exec(cb)
    }
}

module.exports = MerchantSchema